package com.caszx.chargingpile.fragment.reservate;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSONException;
import com.app.base.adapter.BaseClickRecyclerAdapter;
import com.app.base.adapter.BaseHeadFootAdapter;
import com.app.base.fragment.BaseNetViewFragment;
import com.app.jsonparse.JSONParse;
import com.app.utils.DiskUser;
import com.baidu.location.BDLocation;
import com.caszx.chargingpile.R;
import com.caszx.chargingpile.activity.UserSignInActivity;
import com.caszx.chargingpile.entity.EntityCommPile;
import com.caszx.chargingpile.entity.EntitySubRecord;
import com.caszx.chargingpile.eventbus.EventBusAction;
import com.caszx.chargingpile.holder.reservate.ReservateIngHolder;
import com.caszx.chargingpile.http.ConstantUrl;
import com.caszx.chargingpile.user.LocationManager;
import com.caszx.chargingpile.utils.DialogHelp;
import com.caszx.chargingpile.utils.SnackbarHelp;
import com.rey.material.app.DialogFragment;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;
import http.okhttp.OkHttpUtils;
import http.okhttp.callback.JsonCallback;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import okhttp3.Call;

/**
 * 预约->预约记录
 */
public class RecordFragment extends BaseNetViewFragment {

    private RecyclerView mRecyclerView;
    private BaseHeadFootAdapter<EntitySubRecord> mRecyclerAdapter;
    private PtrClassicFrameLayout ptrFrame;
    private boolean isVisibleToUser = false;

    public static RecordFragment newInstance() {
        RecordFragment fragment = new RecordFragment();
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (!this.isVisibleToUser && isVisibleToUser) {
            this.isVisibleToUser = isVisibleToUser;
            onLoad();
        }
    }

    /**
     * 定位的回调
     */
    public void onEvent(String action) {
        if (EventBusAction.ACTION_REQUEST_LOCATION_SU.equals(action)) {
            //定位成功
            String city = LocationManager.getInstance().getCityName();
            if (!TextUtils.isEmpty(city)) {
                onLoad();
            }
        } else if (EventBusAction.ACTION_REQUEST_LOCATION_ER.equals(action)) {
            //定位失败
            showErrorView("定位失败");
        } else if (EventBusAction.ACTION_SING_OUT.equals(action)) {
            //用户退出
            if (mRecyclerAdapter != null) {
                mRecyclerAdapter.clear();
            }
        }else  if(EventBusAction.ACTION_SING_IN.equals(action)){
            //用户登录
            String city = LocationManager.getInstance().getCityName();
            if(!TextUtils.isEmpty(city)) {
                onLoad();
            }
        }
    }

    /**
     * 添加到常用
     */
    public void onEvent(EntitySubRecord action) {
        showProgressDialog("添加中...");
        HashMap<String, String> params = new HashMap<>();
        String token = DiskUser.getStringValueByKey(getContext(), "token");
        params.put("stationId", action.stationId);
        params.put("token", token);
        String url = ConstantUrl.URL_USER_ADD_STATION_;
        OkHttpUtils.post()
                .url(url)
                .params(params)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        dissmissProgressDialog();
                        SnackbarHelp.showSnackbarMsg(getActivity(), getResources().getString(R.string.error_network));
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        dissmissProgressDialog();
                        JSONObject resultJsonObject = response.optJSONObject("result");
                        if (resultJsonObject != null) {
                            int code = resultJsonObject.optInt("code");
                            if (code < 0) {
                                //error
                                SnackbarHelp.showSnackbarMsg(getActivity(), resultJsonObject.optString("msg"));
                            } else {
                                SnackbarHelp.showSnackbarMsg(getActivity(), resultJsonObject.optString("msg"));
                                EventBus.getDefault().post(EventBusAction.ACTION_CHANGE_ADD_COMM_SATION);
                            }
                        }
                    }
                });
    }

    @Override
    protected void onLoad() {
        if (isVisibleToUser == false) return;
        String city = LocationManager.getInstance().getCityName();
        if (TextUtils.isEmpty(city)) {
            EventBus.getDefault().post(EventBusAction.ACTION_REQUEST_LOCATION);
            return;
        }

        HashMap<String, String> params = new HashMap<>();
        params.put("token", DiskUser.getStringValueByKey(getActivity(), "token"));
        params.put("latitude", LocationManager.getInstance().getLatitude() + "");
        params.put("longitude", LocationManager.getInstance().getLongitude() + "");
        OkHttpUtils.post()
                .url(ConstantUrl.URL_SUB_RECORD)
                .params(params)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        if (ptrFrame != null) {
                            ptrFrame.refreshComplete();
                        }
                        showErrorView(R.string.error_network);
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        if (ptrFrame != null) {
                            ptrFrame.refreshComplete();
                        }
                        JSONObject resultJsonObject = response.optJSONObject("result");
                        if (resultJsonObject != null) {
                            int code = resultJsonObject.optInt("code");
                            if (code == -100) {
                                DialogHelp.showDialogOnlyMesg(getActivity(), getResources().getString(R.string.error_minus_100), new DialogHelp.DialogActionClickListener() {
                                    @Override
                                    public void onPositiveActionClicked(DialogFragment fragment) {
                                        Intent intent = new Intent(getActivity(), UserSignInActivity.class);
                                        startActivity(intent);
                                    }
                                    @Override
                                    public void onNegativeActionClicked(DialogFragment fragment) {
                                    }
                                });
                                showErrorView(getResources().getString(R.string.error_minus_100));
                                return;
                            }
                            if (code < 0) {
                                //error
                                // DialogHelp.showDialogOnlyMesg(resultJsonObject.optString("msg"), null);
                                showErrorView(resultJsonObject.optString("msg"));
                            } else {
                                try {
                                    List<EntitySubRecord> datas = JSONParse.parseArray(response.optString("subscribeRecordList"), EntitySubRecord.class);
                                    showContentView();
                                    mRecyclerAdapter.setDatas(datas);
                                } catch (JSONException e) {
                                    showErrorView(R.string.error_parser_json);
                                }
                            }
                        }
                    }
                });
    }

    @Override
    protected View initOnloadedView() {
        View view = getActivity().getLayoutInflater().inflate(
                R.layout.common_refrash_recyclerview, null);
        initPtrFrameLayout(view);
        initRecyclerView(view);
        return view;
    }

    private void initPtrFrameLayout(View view) {
        ptrFrame = (PtrClassicFrameLayout) view
                .findViewById(R.id.ptr_classic_frameLayout);
        ptrFrame.setLastUpdateTimeRelateObject(this);
        ptrFrame.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                onLoad();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame,
                                             View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(ptrFrame,
                        mRecyclerView, header);
            }
        });
    }

    private void initRecyclerView(View view) {
        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        mRecyclerView.setBackgroundResource(R.color.gray3);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerAdapter = new BaseHeadFootAdapter<>(R.layout.item_reservate_record, ReservateIngHolder.class);
        mRecyclerView.setAdapter(mRecyclerAdapter);
    }


    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }
}
